
import whisper
from pathlib import Path
from save_transcript import save_transcript


try:
    from french_transcription import french_transcription_pipeline
    ENHANCED_MODE_AVAILABLE = True
except ImportError:
    ENHANCED_MODE_AVAILABLE = False
    print("⚠️  增强模式不可用：请安装 librosa, noisereduce, transformers")


try:
    from hubert_transcription import hubert_transcription_pipeline
    HUBERT_MODE_AVAILABLE = True
except ImportError:
    HUBERT_MODE_AVAILABLE = False

def transcribe_audio_to_json(
    audio_path: str,
    model_size: str = "small",
    output_dir: str = None,
    use_enhanced_mode: bool = False,
    use_hubert_mode: bool = False,
    enable_noise_reduction: bool = True,
    source_language: str = None
):

    print(f"\n🔍 转录参数:")
    print(f"   音频路径: {audio_path}")
    print(f"   模型大小: {model_size}")
    print(f"   增强模式: {use_enhanced_mode}")
    print(f"   HuBERT模式: {use_hubert_mode}")
    print(f"   源语言: {source_language}")


    audio_file = Path(audio_path)


    if not audio_file.is_absolute():
        audio_dir = Path(__file__).parent.parent / "音频仓库"
        audio_file = audio_dir / audio_path


    audio_filename = audio_file.name


    if output_dir:
        json_output_dir = Path(__file__).parent.parent / output_dir
    else:
        json_output_dir = Path(__file__).parent.parent / "Jason转录数据"


    if not audio_file.exists():
        print(f"错误：音频文件不存在 - {audio_file}")
        return None

    try:

        if use_hubert_mode:
            if not HUBERT_MODE_AVAILABLE:
                print("❌ HuBERT模式不可用，回退到增强模式")
                use_hubert_mode = False
                use_enhanced_mode = True
            else:
                print(f"\n{'='*60}")
                print("🧠 使用HuBERT模式（Wav2Vec2-CTC法语专用）")
                print(f"{'='*60}\n")

                try:

                    result_text = hubert_transcription_pipeline(
                        str(audio_file),
                        enable_noise_reduction=enable_noise_reduction
                    )

                    print(f"\n✓ 转录结果：{result_text[:100]}...")


                    json_filepath = save_transcript(
                        audio_filename,
                        result_text,
                        json_output_dir,
                        f"{model_size}-hubert"
                    )

                    return json_filepath

                except Exception as e:
                    print(f"\n⚠️  HuBERT模式失败: {type(e).__name__}")
                    print(f"   原因: {str(e)[:100]}")
                    print(f"\n🔄 自动回退到增强模式...")
                    use_hubert_mode = False
                    use_enhanced_mode = True


        if use_enhanced_mode and not use_hubert_mode:
            if not ENHANCED_MODE_AVAILABLE:
                print("❌ 增强模式不可用，回退到标准模式")
                print("   请安装依赖: pip install librosa noisereduce transformers")
                use_enhanced_mode = False
            else:
                print(f"\n{'='*60}")
                print("🚀 使用增强模式（HuBERT + Whisper）")
                print(f"{'='*60}\n")

                try:

                    result_text = french_transcription_pipeline(
                        str(audio_file),
                        model_size=model_size,
                        enable_noise_reduction=enable_noise_reduction
                    )

                    print(f"\n✓ 转录结果：{result_text}")


                    json_filepath = save_transcript(
                        audio_filename,
                        result_text,
                        json_output_dir,
                        f"{model_size}-enhanced"
                    )

                    return json_filepath

                except Exception as e:
                    print(f"\n⚠️  增强模式失败: {type(e).__name__}")
                    if "huggingface.co" in str(e) or "Connection" in str(e) or "max_length" in str(e):
                        print("   原因: 无法连接到 HuggingFace 或模型配置问题")
                        print("   建议: 使用标准模式（选择模式1）")
                    print(f"\n🔄 自动回退到标准模式...")
                    use_enhanced_mode = False



        if not use_enhanced_mode and not use_hubert_mode:
            print(f"\n{'='*60}")
            print("📌 使用标准模式（Whisper 内置预处理）")
            print(f"{'='*60}\n")

            print(f"正在加载 Whisper 模型 [{model_size}] ...")
            model = whisper.load_model(model_size)

            print(f"正在转录音频文件: {audio_file}")

            transcribe_options = {
                'verbose': False
            }
            if source_language:
                transcribe_options['language'] = source_language
                print(f"   指定源语言: {source_language}")

            result = model.transcribe(str(audio_file), **transcribe_options)

            print(f"\n✓ 转录结果：{result['text']}")


            json_filepath = save_transcript(
                audio_filename,
                result["text"],
                json_output_dir,
                model_size
            )

            return json_filepath

    except ModuleNotFoundError as e:
        print(f"错误：缺少必要模块 - {e}")
        print("请运行: pip install openai-whisper")
        return None

    except Exception as e:
        print(f"发生错误: {type(e).__name__}: {e}")
        import traceback
        traceback.print_exc()
        return None





def transcribe_audio_to_json_standard(audio_path: str, model_size: str = "small", output_dir: str = None):
    return transcribe_audio_to_json(audio_path, model_size, output_dir, use_enhanced_mode=False)

def transcribe_audio_to_json_enhanced(audio_path: str, model_size: str = "small", output_dir: str = None):
    return transcribe_audio_to_json(audio_path, model_size, output_dir, use_enhanced_mode=True)





if __name__ == "__main__":
    print("""
    ╔══════════════════════════════════════════════════════════════╗
    ║          增强版音频转录测试                                   ║
    ╚══════════════════════════════════════════════════════════════╝
    """)

    test_audio = "../音频仓库/测试mp3（French）.mp3"


    print("\n【测试1：增强模式】")
    result1 = transcribe_audio_to_json(
        test_audio,
        model_size="small",
        use_enhanced_mode=True
    )
    if result1:
        print(f"✓ JSON文件: {result1}")









